package com.jeecg.p3.system.order.web;

import com.jeecg.p3.base.util.PayUtils;
import com.jeecg.p3.system.order.entity.CourseOrder;
import com.jeecg.p3.system.order.entity.F2FQueryVo;
import com.jeecg.p3.system.order.entity.JsapiResultVo;
import com.jeecg.p3.system.order.service.CourseOrderService;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @ClassName JsapiPayController
 * @Description: TODO
 * @Author dell
 * @Date 2020/12/1 
 * @Version V1.0
 **/

@Controller
@RequestMapping("/system/order/pay")
public class JsapiPayController {

    private static final Logger log = LoggerFactory.getLogger(JsapiPayController.class);

    @Autowired
    private CourseOrderService courseOrderService;
    /**
     * 微信公众号支付下单接口
     *
     * @param orderPrice
     * @param openId
     * @param orderNo
     * @return
     */
    @RequestMapping(value = "/weiXinOrders")
    @ResponseBody
    public AjaxJson orders(String orderPrice, String openId, String orderNo ) {
        AjaxJson result = new AjaxJson();
        //获取商户传入参数
        JsapiResultVo jsapiResultVo = courseOrderService.getJsapiPayResultVo(orderNo, orderPrice, openId);
        log.debug("公众号支付--支付结果==>{}", jsapiResultVo);
        try {
            result.setObj(jsapiResultVo);
            if (jsapiResultVo.getReturn_code().equals("SUCCESS")) {
                result.setMsg("微信下单成功");
                result.setSuccess(true);
                log.info("微信下单成功");
            } else if (jsapiResultVo.getReturn_code().equals("WAITING_PAYMENT")) {
                result.setMsg("等待支付,请查看交易结果");
                result.setSuccess(false);
                log.info("等待支付");
            } else if (jsapiResultVo.getReturn_code().equals("FAILED")) {
                result.setMsg("支付失败,失败原因：" + jsapiResultVo.getReturn_msg());
                result.setSuccess(false);
                log.info("支付失败");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("支付失败");
            e.printStackTrace();
            log.error("支付失败");
        }
        return result;
    }

    /**
     *微信支付成功后，向后台发起请求，异步通知，处理业务逻辑
     */
    @RequestMapping("/notify")
    public void callBack(HttpServletRequest request, HttpServletResponse response) {
        InputStream is = null;
        String back = null;
        try {
            String result = PayUtils.getPostStr(request);
            System.out.println(result);
            Map<String, String> notifyMap = PayUtils.xmlToMap(result);
            log.info("异步通知", notifyMap);
            //获取请求的流信息(这里是微信发的xml格式,所有只能使用流来读)
            is = request.getInputStream();
            String s = courseOrderService.payBack(notifyMap);
            back = s;
            response.getWriter().write(back);
            log.info("SUCCESS");
        } catch (Exception e) {
            log.error("微信支付回调通知失败", e);
            back = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            try {
                response.getWriter().write(back);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 查询接口
     * @param  orderNo
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryOrderApp")
    public AjaxJson queryOrderApp(String orderNo) throws ParseException {
        //通过订单号，主动查询订单支付状态，修改订单表
        F2FQueryVo f2FQueryVo=courseOrderService.queryJsapi(orderNo);
        log.debug("查询订单--查询结果==>{}",f2FQueryVo);
        AjaxJson result = new AjaxJson();
        if(f2FQueryVo.getStatus().equals("SUCCESS")){
            result.setObj(f2FQueryVo);
            result.setMsg("查询成功");
            result.setSuccess(true);
            log.info("查询成功");
        }else{
            result.setSuccess(false);
            result.setMsg("查询失败");
            log.error("查询失败");
        }
        return result;
    }

    /**
     * 退款接口
     * @param
     * @return
     */
    /*@ResponseBody
    @RequestMapping("/refundPay")
    public AjaxJson doRefundPayApp(String refundFee,String totalFee,String orderNo,String refundOrderNo ) {
        SortedMap<String, Object> paramMap = new TreeMap<>();
        BigDecimal total_fee =BigDecimal.valueOf(Double.valueOf(totalFee));
        BigDecimal refund_fee =BigDecimal.valueOf(Double.valueOf(refundFee));
        paramMap.put("out_refund_no", refundOrderNo);
        paramMap.put("out_trade_no", orderNo);
        paramMap.put("total_fee",total_fee);
        paramMap.put("refund_fee",refund_fee);
        SortedMap refund = courseOrderService.refund(paramMap);
        CourseOrder rpTradePaymentRecord = goodLstDao.findLstById(orderNo);
        *//*return_code.equals("SUCCESS") && result_code.equals("SUCCESS")*//*
        String return_code = refund.get("return_code").toString();
        String result_code = refund.get("result_code").toString();
        //发起退款
        log.debug("条码退款--退款结果==>{}", refund);

        AjaxJson result = new AjaxJson();
        try {
            result.setObj(refund);
            if(return_code.equals("SUCCESS") && result_code.equals("SUCCESS")){
                //修改状态为已退款
                rpTradePaymentRecord.setStatus(0);//更新状态为已退款
                goodLstDao.update(rpTradePaymentRecord);
                result.setMsg("退款成功");
                result.setSuccess(true);
                log.info("退款成功");
            }
            else{
                result.setMsg("退款失败");
                result.setSuccess(false);
                log.info("退款失败");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("退款失败");
            e.printStackTrace();
            log.error("退款失败");
        }
        return result;
    }*/
}
